package com.oinux.playhelper.app;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Stack;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.oinux.playhelper.db.DatabaseHelper;
import com.oinux.playhelper.entity.AppInfo;
import com.oinux.playhelper.entity.AppStat;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.app.ActivityManager.MemoryInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Debug;
import android.os.Process;
import android.util.Log;

public class AppContext extends Application {

	private static final String TAG = "play_helper";

	private boolean switchTheme = false;
	private Stack<Activity> activityStack;
	private DatabaseHelper databaseHelper = null;

	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public void onTerminate() {
		super.onTerminate();
		if (databaseHelper != null) {
			OpenHelperManager.releaseHelper();
			databaseHelper = null;
		}
		finishAllActivity();
		Process.killProcess(Process.myPid());
	}

	private DatabaseHelper getHelper() {
		if (databaseHelper == null) {
			databaseHelper = OpenHelperManager.getHelper(this,
					DatabaseHelper.class);
		}
		return databaseHelper;
	}

	public void count() {
		try {
			Dao<AppInfo, Integer> appInfoDao = getHelper().getAppInfoDao();
			Dao<AppStat, Integer> appStatDao = getHelper().getAppStatDao();
			List<AppInfo> appInfoList = appInfoDao.queryForAll();
			Date now = new Date();
			for (AppInfo appInfo : appInfoList) {
				appInfo.setTotalTime(appInfo.getTotalTime()
						+ appInfo.getRunTime());
				appInfo.setRunTime(0);
				appInfo.setMemSize(0);
				appInfo.setPid(0);
				appInfo.setUid(0);
				appInfo.setRunning(false);
				appInfoDao.update(appInfo);
			}
			QueryBuilder<AppStat, Integer> queryBuilder = appStatDao
					.queryBuilder();
			queryBuilder.where().isNull("finishTime");
			PreparedQuery<AppStat> preparedQuery = queryBuilder.prepare();
			List<AppStat> appStats = appStatDao.query(preparedQuery);
			for (AppStat appStat : appStats) {
				appStat.setFinishTime(now);
				appStatDao.update(appStat);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}


	public void crash() {
		try {
			Dao<AppInfo, Integer> appInfoDao = getHelper().getAppInfoDao();
			Dao<AppStat, Integer> appStatDao = getHelper().getAppStatDao();
			DeleteBuilder<AppInfo, Integer> deleteAppInfo = appInfoDao
					.deleteBuilder();
			deleteAppInfo.delete();
			appInfoDao.delete(deleteAppInfo.prepare());
			DeleteBuilder<AppStat, Integer> deleteAppStat = appStatDao
					.deleteBuilder();
			deleteAppStat.delete();
			appStatDao.delete(deleteAppStat.prepare());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void finishAllActivity() {
		for (int i = 0, size = activityStack.size(); i < size; i++) {
			if (null != activityStack.get(i)) {
				activityStack.get(i).finish();
			}
		}
		activityStack.clear();
	}

	public void addActivity(Activity activity) {
		if (activityStack == null) {
			activityStack = new Stack<Activity>();
		}
		activityStack.add(activity);
	}

	// 获取android当前可用内存百分比
	public int getAvailMemory() {
		ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		MemoryInfo memoryInfo = new MemoryInfo();
		activityManager.getMemoryInfo(memoryInfo);
		return (int) (memoryInfo.availMem * 100 / getTotalMemory());
	}

	public int getTotalMemory() {
		String readLine = null;
		String[] arrayOfString;
		int totalMemory = 0;
		try {
			FileReader localFileReader = new FileReader("/proc/meminfo");
			BufferedReader localBufferedReader = new BufferedReader(
					localFileReader, 8192);
			readLine = localBufferedReader.readLine();
			arrayOfString = readLine.split("\\s+");
			totalMemory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;
			localBufferedReader.close();
		} catch (IOException e) {
			e.printStackTrace();
			return -1;
		}
		return totalMemory;
	}

	public void releaseMemory() {
		ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		List<ActivityManager.RunningAppProcessInfo> appProcessInfos = activityManager
				.getRunningAppProcesses();
		if (appProcessInfos != null)
			for (int i = 0; i < appProcessInfos.size(); i++) {
				ActivityManager.RunningAppProcessInfo apinfo = appProcessInfos
						.get(i);
				String[] pkgList = apinfo.pkgList;
				if (apinfo.importance >= ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE) {
					for (int j = 0; j < pkgList.length; j++) {
						if (pkgList[j].equals(getPackageName()))
							continue;
						else
							activityManager.killBackgroundProcesses(pkgList[j]);
					}
				}
			}
	}

	/**
	 * 获取当前版本名称
	 */
	public int getVersionCode() {
		PackageInfo info = null;
		try {
			info = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return -1;
		}
		return info.versionCode;
	}

	public String getVersionName() {
		PackageInfo info = null;
		try {
			info = this.getPackageManager().getPackageInfo(
					this.getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return null;
		}
		return info.versionName;
	}

	public boolean isSwitchTheme() {
		return switchTheme;
	}

	public void setSwitchTheme(boolean switchTheme) {
		this.switchTheme = switchTheme;
	}
}
